#delimit;

clear;
capture log close;
set mem 300000;
set mat 700;

set more off;




log using "C:\Old C Drive\F\INTIKAM2009\RESTAT\WEB_Final\Table9_C.log",replace;



use "C:\Old C Drive\F\INTIKAM2009\RESTAT\WEB_Final\Fig4data1.dta" ;




local v "elf85";
foreach var of varlist `v' {;
egen qq=tag(count_code);
preserve;
keep if qq==1;
forval x=20(20)80 {;
egen percentile`x'=pctile(`var'),p(`x');
};
gen d_`var'=.;
replace d_`var'=1 if `var'<percentile20;
replace d_`var'=2 if `var'>=percentile20;
replace d_`var'=3 if `var'>=percentile40;
replace d_`var'=4 if `var'>=percentile60;
replace d_`var'=5 if `var'>=percentile80;
keep count_code year country elf85 percentile20- d_`var';

list country count_code year elf85 if  d_`var'==1;
list country count_code year elf85 if  d_`var'==2;
list country count_code year elf85 if  d_`var'==3;
list country count_code year elf85 if  d_`var'==4;
list country count_code year elf85 if  d_`var'==5;


save `var'_ptiles,replace;
restore;
joinby count_code year using `var'_ptiles;




 
tab country, gen(country) ;



local personal "male  protection
 gun_coll up50 edu avrburgtly_region 
_20to24age _25to29age _30to34age _35to39age _40to44age _45to49age _50to54age _55to59age  _60to64age 
_65to69age _70plusage single widow livtogether divorced  working lookforjob homekeeper ret_disab";


local country_level " country1-country64 europe c_europe mediter newasia2 africa lat_amer year1-year11";



local dependents "gotopris2 ";
foreach varr of varlist `dependents' {;
gen dfdx_`var'_`varr'=.;
gen se_dfdx_`var'_`varr'=.;

forval x=1/5 {;
dprobit `varr' burgtly `personal' `country_level' if d_`var'==`x' 
[pweight=w005] ,robust cluster(count_code);
mat define dd=e(dfdx);
mat define se_d=e(se_dfdx);
replace dfdx_`var'_`varr'=dd[1,1] if d_`var'==`x';
replace se_dfdx_`var'_`varr'=se_d[1,1] if d_`var'==`x';
matrix drop dd se_d;
};
egen qqq_`var'_`varr'=tag(dfdx_`var'_`varr');

sort d_elf85;

by d_elf85: sum elf85;



};

};


log close;



